﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PictureManager.Core
{
    public class Util
    {
        public static List<String> PicExtension = new List<string>(new String[] { ".png", ".jpg", ".jpeg", ".ico", ".bmp", ".gif" });

        public static Boolean LoadDirectory(String directory, String parentID)
        {
            if (!System.IO.Directory.Exists(directory)) return false;
            try
            {
                System.IO.DirectoryInfo direct = new System.IO.DirectoryInfo(directory);
                PictureItem item;
                if (PictureItem.PictureList.Any(p => p.Path == direct.FullName))
                {
                    item = PictureItem.PictureList.FirstOrDefault(p => p.Path == direct.FullName);
                    if (item.ParentID == PictureSettings.Instance.PictureRootNode)
                        item.ParentID = parentID;
                }
                else
                {
                    item = new PictureItem
                    {
                        DateCreated = direct.CreationTime,
                        DateModified = direct.LastWriteTime,
                        ID = Guid.NewGuid().ToString(),
                        ParentID = parentID,
                        Name = direct.Name,
                        Path = direct.FullName
                    };
                    PictureItem.PictureList.Add(item);
                }
                System.IO.Directory.GetFiles(directory).ToList().ForEach(f =>
                {
                    if (!System.IO.File.Exists(f)) return;
                    System.IO.FileInfo file = new System.IO.FileInfo(f);
                    if (!PicExtension.Contains(file.Extension.ToLower()) ||
                        item.FileNames.ContainsKey(file.FullName)) return;
                    UtilLib.IOUtil.SetFile2Normal(file.FullName);
                    item.FileNames.Add(file.FullName, System.IO.Path.GetFileNameWithoutExtension(file.FullName));
                });
                System.IO.Directory.GetDirectories(directory).ToList().ForEach(d =>
                {
                    LoadDirectory(d, item.ID);
                });

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool SyncPictureDataToFolder(List<PictureItem> pictureList)
        {
            try
            {
                pictureList.ForEach(p =>
                {
                    p.Path = System.IO.Path.Combine(PictureSettings.Instance.StorageFolder, p.RelativePath).Replace(@"/", @"\");
                    p.FileNames.ToList().ForEach(f =>
                    {

                        if (!System.IO.File.Exists(f.Key) ||
                            (f.Key == System.IO.Path.Combine(p.Path, System.IO.Path.GetFileName(f.Key)).Replace(@"/", @"\") &&
                            System.IO.Path.GetFileNameWithoutExtension(f.Key) == f.Value) ||
                            (f.Key == System.IO.Path.Combine(p.Path, System.IO.Path.GetFileName(f.Key)).Replace(@"/", @"\") &&
                            System.IO.Path.GetFileNameWithoutExtension(f.Key) != f.Value && !p.IsNameBeFileName))
                            return;

                        string newKey = System.IO.Path.Combine(p.Path, f.Value).Replace(@"/", @"\") + System.IO.Path.GetExtension(f.Key);
                        if (p.FileNames.ContainsKey(newKey)) return;
                        if (f.Key == System.IO.Path.Combine(p.Path, System.IO.Path.GetFileName(f.Key)).Replace(@"/", @"\") &&
                            System.IO.Path.GetFileNameWithoutExtension(f.Key) != f.Value &&
                            p.IsNameBeFileName)
                        {
                            string newFilePath = System.IO.Path.Combine(p.Path, f.Value).Replace(@"/", @"\") + System.IO.Path.GetExtension(f.Key);
                            if (System.IO.File.Exists(newFilePath))
                                System.IO.File.Delete(newFilePath);
                            if (System.IO.Path.GetDirectoryName(f.Key).IndexOf(AppDomain.CurrentDomain.BaseDirectory) == -1)
                                System.IO.File.Copy(f.Key, newFilePath, true);
                            else
                            {
                                System.IO.File.Move(f.Key, newFilePath);
                                if (!UtilLib.IOUtil.IsHaveFiles(System.IO.Path.GetDirectoryName(f.Key), true))
                                {
                                    System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(f.Key), true);
                                }
                            }
                            p.FileNames.Remove(f.Key);
                            p.FileNames.Add(newFilePath, f.Value);
                        }
                        else
                        {
                            p.FileNames.Remove(f.Key);
                            bool isCopy = (System.IO.Path.GetDirectoryName(f.Key).IndexOf(AppDomain.CurrentDomain.BaseDirectory) == -1);

                            if (p.IsNameBeFileName && !p.FileNames.ContainsKey(System.IO.Path.Combine(p.Path, f.Value).Replace(@"/", @"\")))
                            {
                                string newFilePath = System.IO.Path.Combine(p.Path, f.Value).Replace(@"/", @"\") + System.IO.Path.GetExtension(f.Key);
                                UtilLib.IOUtil.MoveFileToPath(f.Key, p.Path, f.Value + System.IO.Path.GetExtension(f.Key), isCopy);
                                p.FileNames.Add(newFilePath, f.Value);
                            }
                            else
                            {
                                UtilLib.IOUtil.MoveFileToPath(f.Key, p.Path, isCopy);
                                p.FileNames.Add(System.IO.Path.Combine(p.Path, System.IO.Path.GetFileName(f.Key)).Replace(@"/", @"\"), f.Value);
                            }

                            if (!isCopy && !UtilLib.IOUtil.IsHaveFiles(System.IO.Path.GetDirectoryName(f.Key), true))
                            {
                                System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(f.Key), true);
                            }
                        }
                    });
                });
                return true;
            }
            catch (Exception ex)
            {
                UtilLib.Util.Log(UtilLib.LogLevel.Error, ex);
                return false;
            }
        }

        public static void GetChildPictureItems(List<PictureItem> list, String parentID)
        {
            PictureItem.PictureList.
                Where(p => p.ParentID == parentID).ToList().
                ForEach(k =>
                {
                    list.Add(k);
                    GetChildPictureItems(list, k.ID);
                });

        }

    }
}
